package org.ziegler.log.analysis.fileFilter;

import java.io.File;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import org.ziegler.log.analysis.AppConfig;
import org.ziegler.log.analysis.ConstUtils;
import org.ziegler.log.analysis.LogCore;
import org.ziegler.log.analysis.core.FileUtils;

public class CachedFileFilter implements FileFilter {

    private final List<File> newFiles;

    public CachedFileFilter(boolean cache) {
        final File[] files = FileUtils.listLogFiles(AppConfig.getInstance().getLogPath());

        Set<String> allCacheLogFileName = new HashSet<>(FileUtils.readLines(ConstUtils.CACHE_ALL_LOGFILE_NAME));
        assert allCacheLogFileName.size() == FileUtils.readLines(ConstUtils.CACHE_ALL_LOGFILE_NAME).size() : "有重名的日志文件名";

        // 排除已经读取过的文件
        newFiles = Arrays.stream(files)
                .filter(f -> !allCacheLogFileName.contains(f.getName()))
                .collect(Collectors.toList());

        // 保存缓存文件
        if (cache) {
            // 追加写入日志文件名称
            final List<String> newFileNames = newFiles.stream().map(File::getName).collect(Collectors.toList());
            FileUtils.appendWriteLines(ConstUtils.CACHE_ALL_LOGFILE_NAME, newFileNames);
            LogCore.info("缓存" + ConstUtils.CACHE_ALL_LOGFILE_NAME + "，总数量 = " + newFileNames.size());
        }
    }

    @Override
    public List<File> getFiles() {
        return newFiles;
    }
}
